const net = require("node:net");


const { on_set_rfid_judgment } = require('./utils/set-rfid.cjs')

// 心跳时长
const heartbeatInterval = 1000;

const connect = (config) => {
  const client = new net.Socket();


  const onContentClient = () => {
    client.connect(config.port, config.host, () => {
      console.log("connected");

      // 开始发送心跳
      setInterval(() => {

        const onSend = (data) => {
          const buffer = Buffer.from(data, 'hex');
          client.write(buffer);
        }

        onSend("A50401005501")
        // onSend("A50401005601")
        // 停止
        // onSend("A504010060F6")

      }, heartbeatInterval);
    });
  };

  client.on('data', (message, remote) => {
    // console.log('message', message)
    // console.log(`Received ${message.length} bytes from ${remote.address}:${remote.port}`);
    parsePacket(message);
  });

  client.on("end", () => {
    console.log("Connection closed.");
    retryContent();
  });

  client.on("error", (err) => {
    console.error("Error occurred:", err);
    client.destroy(); // 销毁客户端
    retryContent();
  });

  function parsePacket(packetData) {
    // 检查数据包是否以 0xA5 开头
    if (packetData[0] !== 0xA5) {
      // console.error('数据包格式错误，包头应为 0xA5');
      return;
    }

    // 提取数据包长度
    let len = packetData[1];

    // 提取 485 地址码
    let address = (packetData[2] << 8) | packetData[3];

    // 提取指令码
    let cmd = packetData[4];

    // 提取数据部分（如果有）
    let data = packetData.slice(5, 5 + len - 4);

    // 计算校验和
    let calculatedCK = calculateCK(packetData.slice(0, -1));
    let receivedCK = packetData[packetData.length - 1];

    // 检查校验和是否匹配
    if (calculatedCK !== receivedCK) {
      // console.error('校验和错误');
      return;
    }



    const antennaNumber = packetData[7];

    // console.log("antennaNumber", antennaNumber);

    // 输出解析结果
    // console.log('包头:', packetData[0]);
    // console.log('数据包长度:', len);
    // console.log('485 地址码:', address);
    // console.log('指令码:', cmd);
    // console.log('数据:', data);
    // console.log('校验和:', receivedCK);`


    const epcIndex = 5
    const epcEndIndex = len - epcIndex - 3
    const epc_data = data.slice(epcIndex, epcEndIndex);
    const rfid = epc_data.toString('hex').toUpperCase()
    // console.log('rfid', rfid);

    const key = `${config.host}-${antennaNumber}`;
    const sendResult = {
      key,
      ip: config.host,
      port: config.port,
      antenna: antennaNumber,
      rfid: rfid,
    };

    // if (antennaNumber !== 1) return
    // const rfids = ['E2806894200040224A32B4FB', 'E28068940000500F4526782E']
    const rfids = []
    if (rfids.length && !rfids.includes(rfid)) return

    on_set_rfid_judgment(sendResult)

    // data 转化为16进制大写字符串
    // console.log('数据:', data.toString('hex').toUpperCase());
  }

  function calculateCK(buffer) {
    let sum = 0;
    for (let i = 0; i < buffer.length; i++) {
      sum += buffer[i];
    }
    return (~sum + 1) & 0xFF;
  }

  function retryContent() {
    setTimeout(onContentClient, 1000);
  }

  onContentClient();
};

connect({
  host: "192.168.100.20",
  port: 4001,
});

// 添加一个监听器以优雅地处理程序退出，清除定时器
process.on("SIGINT", function () {
  console.log("\nGracefully shutting down from SIGINT (Ctrl-C)");
  process.exit();
});
